<template>
  <el-dialog
    v-model="shown"
    draggable
    append-to-body
    show-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="编辑便签"
    width="600px"
    @close="$emit('close')"
  >
    <div class="container-edit">
      <div style="width: 300px">
        <div class="input-label">便签内容</div>
        <div>
          <el-input
            v-model="editorData.text"
            :size="size"
            style="width: 100%"
          ></el-input>
        </div>
      </div>
      <div style="width: 120px">
        <div class="input-label">便签类型</div>
        <div>
          <el-select v-model="editorData.type" :size="size" style="width: 100%">
            <el-option label="一般" value="一般"></el-option>
            <el-option label="重要" value="重要"></el-option>
          </el-select>
        </div>
      </div>
      <div style="width: 120px">
        <div class="input-label">有效期(小时)</div>
        <div>
          <el-input-number
            v-model="editorData.until"
            controls-position="right"
            :min="0.5"
            :max="9999"
            :step="0.5"
            :size="size"
            style="width: 100%"
          />
        </div>
      </div>
      <div style="width: 80px">
        <div class="input-label">&emsp;</div>
        <div>
          <el-button
            type="primary"
            :size="size"
            @click="handleAdd"
            v-if="editorIndex == -1"
            style="width: 100%"
            :disabled="editorData.text.length < 5"
          >
            <span>添加</span>
          </el-button>
          <el-button
            type="primary"
            :size="size"
            @click="handleSaveModify"
            v-else
            style="width: 100%"
            :disabled="editorData.text.length < 5"
          >
            <span>保存</span>
          </el-button>
        </div>
      </div>
    </div>
    <div class="container-list">
      <el-table :data="notes" :size="size" style="width: 100%" height="250">
        <el-table-column label="内容" minn-width="300px">
          <template #default="scope">
            <div
              :style="{
                display: 'flex',
                alignItems: 'center',
                color:
                  scope.row.type == '一般'
                    ? 'var(--el-color-info)'
                    : 'var(--el-color-warning)',
                textDecoration: dayjs().isAfter(scope.row.until)
                  ? 'line-through 2px'
                  : 'none',
                opacity: dayjs().isAfter(scope.row.until) ? '0.5' : '1',
              }"
            >
              {{ scope.row.text }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="剩余" width="80px" align="center">
          <template #default="scope">
            <span
              >{{
                -dayjs().diff(scope.row.until, "hour", true).toFixed(1)
              }}h</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90px" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleModify(scope.$index)">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button link type="danger" @click="handleDelete(scope.$index)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <pre>{{ notes }}</pre> -->
  </el-dialog>
</template>

<script setup>
import { h, ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";

const Props = defineProps(["notes"]);
const size = ref("small");
const shown = ref(false);
const open = () => {
  shown.value = true;
  resetEditor();
  if (Props.notes && Props.notes.length > 0) {
    notes.value = Props.notes;
  } else {
    loadNotes();
  }
};

defineExpose({ open });

const editorData = ref({
  number: -1,
  text: "",
  type: "一般",
  until: 2,
});

const handleAdd = () => {
  let note = JSON.parse(JSON.stringify(editorData.value));
  note.until = dayjs().add(note.until, "hour").format("YYYY-MM-DD HH:mm:ss");
  note.number = -1;
  axios
    .post("api/global_notes_handler.php?action=add", note)
    .then((response) => {
      if (response.data.success) {
        note.number = response.data.result;
        notes.value.unshift(note);
        resetEditor();
        ElMessage.success("已添加");
      }
      // console.log("GlobalNote:", response.data);
    })
    .catch((error) => {
      console.error("GlobalNoteError:", error);
      ElMessage.error("出错了~");
    });
};

const editorIndex = ref(-1);
const handleModify = (index) => {
  editorData.value = JSON.parse(JSON.stringify(notes.value[index]));
  editorData.value.until = -dayjs().diff(editorData.value.until, "hour");
  editorIndex.value = index;
};

const handleSaveModify = () => {
  let note = JSON.parse(JSON.stringify(editorData.value));
  note.until = dayjs().add(note.until, "hour").format("YYYY-MM-DD HH:mm:ss");
  axios
    .post("api/global_notes_handler.php?action=save", note)
    .then((response) => {
      if (response.data.success) {
        notes.value[editorIndex.value] = note;
        resetEditor();
        ElMessage.success("已保存");
      }
      // console.log("GlobalNote:", response.data);
    })
    .catch((error) => {
      console.error("GlobalNoteError:", error);
      ElMessage.error("出错了~");
    });
};

const handleDelete = (index) => {
  ElMessageBox.confirm(
    `确认要删除便签“${notes.value[index].text}”吗？`,
    "删除确认",
    {
      confirmButtonText: "删除",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      axios
        .post("api/global_notes_handler.php?action=delete", notes.value[index])
        .then((response) => {
          if (response.data.success) {
            notes.value.splice(index, 1);
            resetEditor();
            ElMessage.success("已删除");
          } else {
            console.warn("GlobalNoteWarn:", response.data);
            ElMessage.error("出错了~");
          }
        })
        .catch((error) => {
          console.error("GlobalNoteError:", error);
          ElMessage.error("出错了~");
        });
    })
    .catch(() => {});
};

const resetEditor = () => {
  editorIndex.value = -1;
  editorData.value = {
    number: -1,
    text: "",
    type: "一般",
    until: 2,
  };
};

const notes = ref([]);

const loadNotes = () => {
  axios
    .get("api/global_notes_handler.php")
    .then((response) => {
      // console.log("GlobalNote:", response.data);
      if (response.data.success) {
        notes.value = response.data.result;
      } else {
        // ElMessage.warning("出错了~");
        console.warn("GlobalNoteWarn:", response.data);
      }
    })
    .catch((error) => {
      console.error("GlobalNoteError:", error);
      // ElMessage.error("出错了~");
    });
};

onMounted(() => {
  loadNotes();
  resetEditor();
});
</script>

<style scoped>
.container-edit {
  display: flex;
  align-items: center;
}

.container-edit > * {
  margin-right: 10px;
}

.container-edit > lase-child {
  margin-right: 0;
}

.container-list {
  margin-top: 24px;
}

.input-label {
  font-size: 12px;
  color: var(--el-color-info);
  padding-bottom: 4px;
  padding-left: 4px;
  /* transform: scale(0.75); */
}
</style>
